<template>
  <div>
    <div class="search-container">
      <div class="search-inp-container">
        <el-input @keyup.enter.native="handleSearch" placeholder="输入渠道商名称" v-model="listQuery.channelName" clearable>
        </el-input>
      </div>
      <el-button class="search-btn" type="primary" icon="el-icon-search" @click="handleSearch">查询</el-button>
      <el-button class="search-btn" type="primary" icon="el-icon-plus" v-if="mall_channel_add" @click="handleAdd">添加</el-button>
      <el-button class="search-btn" :autofocus="true" icon="el-icon-refresh" @click="refreshHandle">刷新</el-button>
    </div>
    <el-table :key='tableKey' :data="list" v-loading="listLoading" border fit highlight-current-row>
      <el-table-column align="center" prop="channelName" label="渠道商名称" width="180">
      </el-table-column>
      <el-table-column align="center" prop="addr" label="地址" width="180">
      </el-table-column>
      <el-table-column align="center" prop="userName" label="联系人">
      </el-table-column>
      <el-table-column align="center" prop="mobile" label="联系电话">
      </el-table-column>
      <el-table-column align="center" prop="type" label="类型">
        <template slot-scope="scope">
          <el-span >
            {{scope.row.type | statusFilter}}
          </el-span>
        </template>
      </el-table-column>


      <el-table-column align="center" label="创建时间">
        <template slot-scope="scope">
          <span>{{scope.row.createDate | parseTime('{y}-{m}-{d} {h}:{i}')}}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="操作" width="180" v-if="mall_channel_update  || mall_channel_del ">
        <template slot-scope="scope">
          <el-button v-if="mall_channel_update" size="mini" type="primary" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button v-if="mall_channel_del" size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div v-show="!listLoading" class="pagination-container">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page.sync="listQuery.current" :page-size="listQuery.size" :page-sizes="[10, 40, 80, 100]" layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" width="40%" :close-on-click-modal="false">
      <el-form :model="form" :rules="rules" ref="form" label-width="100px">
        <el-form-item label="渠道商名称" prop="channelName">
          <el-input class="w347" maxLength='10' v-model="form.channelName" placeholder="请输渠道商名称"></el-input>
        </el-form-item>
        <!-- <el-form-item label="LOGO" prop="imgUrl">
           <div>
             <el-upload-->
              <!--action="http://114.116.87.47:2004/mall/ad/imgUpload/"-->
              <!--:headers = "headers"-->
              <!--list-type="picture-card"-->
              <!--accept="image/*"-->
              <!--:limit="imgLimit"-->
              <!--:file-list="fileList"-->
              <!--:multiple="isMultiple"-->
              <!--:on-preview="handlePictureCardPreview"-->
              <!--:on-remove="handleRemove"-->
              <!--:on-success="handleAvatarSuccess"-->
              <!--:before-upload="beforeAvatarUpload"-->
              <!--:on-exceed="handleExceed"-->
              <!--:on-error="imgUploadError">-->
              <!--<i class="el-icon-plus"></i>-->
            <!--</el-upload>-->
            <!--<el-dialog :visible.sync="dialogVisible">-->
              <!--<img width="100%" :src="dialogImageUrl" alt="">-->
            <!--</el-dialog>-->
          <!--</div>-->
        <!--</el-form-item>-->

        <el-form-item class="w347"  label="地址" placeholder="请输入地址" prop="addr">
          <el-input  maxLength='20' v-model="form.addr"></el-input>
        </el-form-item>

        <el-form-item class="w347"  label="联系人" placeholder="请输入联系人" prop="userName">
          <el-input maxLength='10' v-model="form.userName"></el-input>
        </el-form-item>

        <el-form-item class="w347"  label="联系电话" placeholder="请输入电话" prop="mobile">
          <el-input  maxLength='11' oninput="value=value.replace(/[^\d]/g,'')"  v-model="form.mobile"></el-input>
        </el-form-item>

        <el-form-item label="类型" prop="type">
          <el-select class="filter-item w347" v-model="form.type" placeholder="请选择" >
            <el-option v-for="item in rolesOptions" :key="item.value" :label="item.dictDesc" :value="item.value" :disabled="isDisabled[item.delFlag]">
              <span style="float: left">{{ item.dictDesc }}</span>
            </el-option>
          </el-select>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel('form')">取 消</el-button>
        <el-button v-if="dialogStatus=='create'" type="primary" @click="create('form')">确 定</el-button>
        <el-button v-else type="primary" @click="update('form')">修 改</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { fetchList, delObj, getObj, addObj, putObj } from '@/api/channel'
import { getToken } from '@/api/mallgoods'
import { getTopDictListByDescNew } from '@/api/dict'
import { mapGetters } from 'vuex'
export default {
  data() {
    return {
      // 图片
      dialogImageUrl: undefined,
      dialogVisible: false,
      url: '',
      imgUpload: process.env.BASE_API + '/mall/ad/imgUpload/',
      headers: {
        'Authorization': getToken()
        // token为系统访问需要的,放在header中
      },
      fileList: [],
      isMultiple: false,
      imgLimit: 1,
      // 图片
      tableKey: 0,
      listLoading: false,
      list: [],
      listQuery: {
        current: 1,
        size: 10,
        channelName: '',
        descs: 'create_date'
      },
      total: 0,
      mall_channel_add: false,
      mall_channel_update: false,
      mall_channel_del: false,
      sys_user_select: false,
      dialogFormVisible: false,
      form: {
        channelName: undefined,
        addr: undefined,
        userName: undefined,
        mobile: undefined,
        type: undefined,
        imgUrl: undefined
      },
      rules: {

        channelName: [
          {
            required: true,
            message: '请输入渠道商名',
            trigger: 'blur'
          }
        ],
        mobile: [
          {
            required: true,
            message: '手机号不能为空',
            trigger: 'blur'
          }
        ],
        userName: [
          {
            required: true,
            message: '联系人不能为空',
            trigger: 'blur'
          }
        ]
      },
      textMap: {
        update: '编辑',
        create: '创建'
      },
      dialogStatus: '',
      role: [],
      rolesOptions: [],
      isDisabled: {
        0: false,
        1: true
      },
      statusOptions: ['0', '1'],
      dialogDeptVisible: false,
      treeDeptData: [],
      checkedKeys: [],
      defaultProps: {
        children: 'childrens',
        label: 'name'
      }
    }
  },

  components: {},
  filters: {
    statusFilter(status) {
      const statusMap = {
        1: '电子券',
        2: '商品',
        9: '其他'
      }
      return statusMap[status]
    }
  },
  computed: {
    ...mapGetters(['permissions'])
  },

  mounted() {
    this.getList()
    this.mall_channel_add = this.permissions['/mall/channel:add']
    this.mall_channel_update = this.permissions['/mall/channel:update']
    this.mall_channel_del = this.permissions['/mall/channel:del']
    this.sys_user_select = this.permissions['/admin/user:select']
  },

  methods: {
    getList() {
      this.listLoading = true
      this.listQuery.isAsc = false
      fetchList(this.listQuery).then(response => {
        this.list = response.data.records
        this.total = response.data.total
        this.listLoading = false
      })
    },
    refreshHandle() {
      this.listQuery.current = 1
      this.listQuery.size = 10
      this.listQuery.username = ''
      this.getList()
    },
    handleAdd() {
      this.form = {}
      this.dialogStatus = 'create'
      this.getDictList()
      this.fileList = []
      this.dialogFormVisible = true
    },
    handleDelete(row) {
      this.$confirm(
        '此操作将永久删除该渠道商, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        delObj(row.channelId)
          .then(() => {
            this.getList()
            this.$notify({
              title: '成功',
              message: '删除成功',
              type: 'success',
              duration: 2000
            })
          })
          .cache(() => {
            this.$notify({
              title: '失败',
              message: '删除失败',
              type: 'error',
              duration: 2000
            })
          })
      })
    },
    handleEdit(row) {
      this.dialogStatus = 'update'
      this.fileList = []
      this.getDictList()
      getObj(row.channelId).then(response => {
        this.form = response.data
        this.dialogFormVisible = true
        this.dialogStatus = 'update'
        this.dialogFormVisible = true
        // 图片回显
        const obj = new Object()
        obj.url = response.data.imgUrl
        if (obj.url != null) {
          this.fileList.push(obj)
        }
        this.dialogFormVisible = true
        this.dialogStatus = 'update'
      })
    },
    handleSearch() {
      this.listQuery.current = 1
      this.getList()
    },
    handleSizeChange(val) {
      this.listQuery.size = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.listQuery.current = val
      this.getList()
    },
    create(formName) {
      const set = this.$refs
      set[formName].validate(valid => {
        if (valid) {
          addObj(this.form).then(() => {
            this.dialogFormVisible = false
            this.getList()
            this.$notify({
              title: '成功',
              message: '创建成功',
              type: 'success',
              duration: 2000
            })
          })
        } else {
          return false
        }
      })
    },
    cancel(formName) {
      this.dialogFormVisible = false
      this.$refs[formName].resetFields()
    },
    update(formName) {
      const set = this.$refs
      set[formName].validate(valid => {
        if (valid) {
          putObj(this.form).then(() => {
            this.dialogFormVisible = false
            this.getList()
            this.$notify({
              title: '成功',
              message: '修改成功',
              type: 'success',
              duration: 2000
            })
          })
        } else {
          return false
        }
      })
    },
    async getDictList() {
      const res = await getTopDictListByDescNew('渠道商类型')
      this.rolesOptions = res.data
    },
    handleRemove(file, fileList) { // 移除图片
      this.fileList = []
      console.log(file, fileList)
    },
    handlePictureCardPreview(file) { // 预览图片时调用
      console.log(file)
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },

    beforeAvatarUpload(file) { // 文件上传之前调用做一些拦截限制
    },
    handleAvatarSuccess(res, file) { // 图片上传成功
      console.log(res)
      console.log(file)
      var url = res.true
      if (url == '' || url == undefined || url == 'undefined') {
        this.$notify({
          title: '失败',
          message:res.false,
          type: 'error',
          duration: 4000
        })
        return
      }
      console.log(url)
      // alert('成功')
      this.form.imgUrl = url// 表单提交
      this.imageUrl = URL.createObjectURL(file.raw)
      this.fileList.push(file)
    },
    handleExceed(files, fileList) { // 图片上传超过数量限制
      this.$message.error('上传图片不能超过1张!')
      console.log(file, fileList)
    },
    imgUploadError(err, file, fileList) { // 图片上传失败调用
      console.log(err)
      this.$message.error('上传图片失败!')
    }

  }
}

</script>


<style lang='scss' scoped>
.w347 {
  width: 100%;
}
</style>
